#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash gromacs-2019.3.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules time patch libatomic autoconf automake libtool numactl binutils systemd-devel valgrind flex wget cmake lmfit
set -e

wget -t 10 -c -P $buildpath http://ftp.gromacs.org/pub/gromacs/gromacs-2019.3.tar.gz
tar xf $buildpath/gromacs-2019.3.tar.gz -C $buildpath && rm -rf $buildpath/gromacs-2019.3.tar.gz
cd $buildpath/gromacs-2019.3/src/gromacs/utility
sed -i 58s/xmmintrin.h/avx2neon.h/ alignedallocator.cpp
cd $buildpath/gromacs-2019.3
mkdir -p build
cd build
FLAGS="-mcpu=tsv110"; CFLAGS=$FLAGS CXXFLAGS=$FLAGS LDFLAGS="-lflang" CC=mpicc CXX=mpicxx \
cmake \
-DCMAKE_INSTALL_PREFIX=$buildpath/gromacs-2019.3 \
-DBUILD_SHARED_LIBS=on \
-DBUILD_TESTING=on \
-DREGRESSIONTEST_DOWNLOAD=off \
-DGMX_BUILD_OWN_FFTW=off \
-DGMX_SIMD=ARM_NEON_ASIMD \
-DGMX_DOUBLE=off \
-DGMX_EXTERNAL_BLAS=on \
-DGMX_EXTERNAL_LAPACK=on \
-DGMX_FFT_LIBRARY=fftw3 \
-DGMX_BLAS_USER=$installpath/openblas-0.3.6/lib/libopenblas.a \
-DGMX_LAPACK_USER=$installpath/openblas-0.3.6/lib/libopenblas.a \
-DFFTWF_LIBRARY=$installpath/fftw-3.3.8/lib/libfftw3f.so \
-DFFTWF_INCLUDE_DIR=$installpath/fftw-3.3.8/include \
-DGMX_GPU=off \
-DGMX_MPI=on \
-DGMX_OPENMP=on \
-DGMX_X11=off \
-DCMAKE_C_COMPILER_WORKS=1 \
-DCMAKE_CXX_COMPILER_WORKS=1 \
../
make -j$(nproc) V=1
make install
mkdir -p $installpath/gromacs-2019.3 && cp -r $buildpath/gromacs-2019.3/* $installpath/gromacs-2019.3
cat>"$installpath/gromacs-2019.3/gromacs_modulefiles"<<EOF
#%Module1.0
conflict gromacs
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set GROMACS \$pwd
setenv GROMACS \$GROMACS
prepend-path PATH \$GROMACS/bin
EOF

rm -rf $buildpath/gromacs-2019.3
